package com.yimaxiaoerlang.rtc_kit.ui;

import androidx.fragment.app.FragmentActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AsyncPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yimaxiaoerlang.module_signalling.YMRTMChannel;
import com.yimaxiaoerlang.module_signalling.core.YMRTMChannelListener;
import com.yimaxiaoerlang.rtc_lib.YMRLClient;
import com.yimaxiaoerlang.rtc_lib.YMVideoRoomHelper;
import com.yimaxiaoerlang.rtc_lib.YMVideoRoomHelperLinstener;
import com.yimaxiaoerlang.rtc_kit.R;
import com.yimaxiaoerlang.rtc_kit.model.CallOpera;
import com.yimaxiaoerlang.rtc_kit.model.CallUser;
import com.yimaxiaoerlang.rtc_kit.CallManager;
import com.yimaxiaoerlang.rtc_kit.utils.GsonUtils;
import com.yimaxiaoerlang.rtc_kit.utils.ImageUtils;
import com.yimaxiaoerlang.rtc_kit.view.PersonalItemView;
import com.yimaxiaoerlang.rtc_kit.view.WrapLayout;

import java.util.ArrayList;
import java.util.HashMap;

public class CallMultiActivity extends FragmentActivity implements YMRTMChannelListener {
    private YMRTMChannel channel;
    private YMVideoRoomHelper videoRoomHelper;
    private AsyncPlayer ringPlayer;
    private CallOpera callOpera;
    private String channelId = "";
    private String callId = "";
    boolean closeCamera = false;
    boolean closeMic = false;
    private HashMap<String, ImageView> wittingIconMap = new HashMap<String, ImageView>();
    private HashMap<String, PersonalItemView> personalMap = new HashMap<String, PersonalItemView>();
    private HashMap<String, CallUser> userMap = new HashMap<>();


    private ImageView ivAnswer;
    private ImageView ivHandup;
    private ImageView ivSwitch;
    private ImageView ivReject;
    private ImageView ivCloseCamera;
    private ImageView ivMic;
    private TextView itvCloseCamera;
    private LinearLayout callingLayout;
    private RelativeLayout wittingLayout;
    private LinearLayout layoutCalling;
    private LinearLayout layoutRecive;
    private ImageView ivCallUserIcon;
    private TextView tvCallTitle;
    private WrapLayout callingWraplayout;
    private WrapLayout wittingWraplayout;
    private TextView tvCallOther;
    private CallUser curUser;

    public static void callMulti(
            Activity activity,
            String channel,
            ArrayList<CallUser> callUsers,
            Boolean call
    ) {
        Intent intent = new Intent(activity, CallMultiActivity.class);
        intent.putExtra("call", call);
        intent.putExtra("channel", channel);
        intent.putExtra("json", GsonUtils.toJson(callUsers));
        activity.startActivity(intent);
    }

    public static void receiveCall(
            Context application, String tid,
            String channel,
            String name,
            String userAvatar,
            ArrayList<CallUser> users
    ) {
        Intent intent = new Intent(application, CallMultiActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("tid", tid);
        intent.putExtra("channel", channel);
        intent.putExtra("call", false);
        intent.putExtra("name", name);
        intent.putExtra("userAvatar", userAvatar);
        intent.putExtra("json", GsonUtils.toJson(users));
        application.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
        );
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_multi);
        initView();
        initCall();
        initData();
    }

    private void initView() {
        ivAnswer = findViewById(R.id.iv_answer);
        ivHandup = findViewById(R.id.iv_handup);
        ivSwitch = findViewById(R.id.iv_switch);
        ivReject = findViewById(R.id.iv_reject);
        ivCloseCamera = findViewById(R.id.iv_close_camera);
        itvCloseCamera = findViewById(R.id.itv_close_camera);
        ivMic = findViewById(R.id.iv_mic);
        callingLayout = findViewById(R.id.calling);//calling calling_layout
        wittingLayout = findViewById(R.id.witting);// witting_layout
        layoutCalling = findViewById(R.id.layout_calling);
        ivCallUserIcon = findViewById(R.id.iv_call_user_icon);
        tvCallTitle = findViewById(R.id.tv_call_title);
        callingWraplayout = findViewById(R.id.calling_wraplayout);
        layoutRecive = findViewById(R.id.layout_recive);
        wittingWraplayout = findViewById(R.id.witting_wraplayout);
        tvCallOther = findViewById(R.id.tv_call_other);


        ivAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<CallUser> array = new ArrayList<>();
                for (String s : userMap.keySet()) {
                    array.add(userMap.get(s));
                }
                callLayout(GsonUtils.toJson(array));
                createHelperAndJoin();
            }
        });
        ivHandup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoRoomHelper != null) videoRoomHelper.leave();
                if (callOpera != null) callOpera.hangup(channelId + "," + callId, true);
                finish();
            }
        });

        ivSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoRoomHelper != null) {
                    videoRoomHelper.switchCamera();
                }
            }
        });
        ivReject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (callOpera != null) callOpera.refuse(channelId + "," + callId, true);
                finish();
            }
        });
        ivCloseCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String message = "";
                if (closeCamera) {
                    ivCloseCamera.setImageResource(R.mipmap.shexiangtou);
                    itvCloseCamera.setText("关闭摄像头");
                    message = "openCamera";
                    openCamera(curUser.getUid(), true);
                } else {
                    ivCloseCamera.setImageResource(R.mipmap.shexiangtou_guanbi);
                    itvCloseCamera.setText("打开摄像头");
                    message = "closeCamera";
                    openCamera(curUser.getUid(), false);
                }
                closeCamera = !closeCamera;
                if (videoRoomHelper != null) videoRoomHelper.openCamera(!closeCamera);

                if (channel != null) {
                    channel.sendMessage(message, null);
                }
            }
        });

        ivMic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (closeMic) {
                    ivMic.setImageResource(R.mipmap.maikefeng);
                    if (videoRoomHelper != null) videoRoomHelper.openMic(true);
                } else {
                    ivMic.setImageResource(R.mipmap.guanbimaikefeng);
                    if (videoRoomHelper != null) videoRoomHelper.openMic(false);
                }

                closeMic = !closeMic;
            }
        });
    }

    private void initData() {
        curUser = CallManager.getInstance().getCurUser();
        boolean call = getIntent().getBooleanExtra("call", false);
        channelId = getIntent().getStringExtra("channel").toString();
        joinChannel();
        String jsonArray = getIntent().getStringExtra("json").toString();
        if (call) {
            callingLayout.setVisibility(View.VISIBLE);
            wittingLayout.setVisibility(View.GONE);
            layoutCalling.setVisibility(View.VISIBLE);
            showJoin();
            callLayout(jsonArray);
            startCall(jsonArray);
            createHelperAndJoin();
        } else {
            callId = getIntent().getStringExtra("tid").toString();
            showWitting(jsonArray, callId);
            ImageUtils.loadImage(ivCallUserIcon, getIntent().getStringExtra("userAvatar").toString());
            tvCallTitle.setText(getIntent().getStringExtra("name") + "邀请你加入语音通话");
        }
    }

    private void initCall() {
        ringPlayer = new AsyncPlayer("");
        callOpera = CallManager.getInstance().getCallOpera();
    }


    private void startCall(String json) {
        if (TextUtils.isEmpty(json)) {
            return;
        }
        ArrayList<CallUser> array = GsonUtils.toList(json, CallUser.class);
        if (curUser != null && callOpera != null) {
            callOpera.callMulti(array, curUser.getNickname(), curUser.getAvatar(), channelId);

        }


    }

    private void callLayout(String json) {
        ArrayList<CallUser> array = GsonUtils.toList(json, CallUser.class);
        for (CallUser callUser : array) {
            PersonalItemView view = new PersonalItemView(this, callUser.getUid(), callUser.getAvatar());
            WindowManager wm = this.getWindowManager();
            int width = wm.getDefaultDisplay().getWidth();

            view.setLayoutParams(new RelativeLayout.LayoutParams((width / 2) - 80, 500));
            callingWraplayout.addView(view);
            personalMap.put(callUser.getUid(), view);
        }
    }


    private void joinChannel() {
        channel = YMRLClient.getInstance().createChannel(channelId);
        channel.setChannelListener(this);
        channel.joinChannel(null);


    }

    private void showJoin() {
        callingLayout.setVisibility(View.VISIBLE);
        layoutCalling.setVisibility(View.VISIBLE);
        layoutRecive.setVisibility(View.GONE);
        wittingLayout.setVisibility(View.GONE);
    }

    private void showWitting(String json, String tid) {
        callingLayout.setVisibility(View.GONE);
        layoutCalling.setVisibility(View.GONE);
        layoutRecive.setVisibility(View.VISIBLE);
        wittingLayout.setVisibility(View.VISIBLE);
        startCallSound();

        ArrayList<CallUser> array = GsonUtils.toList(json, CallUser.class);
        int count = 0;
        for (CallUser it : array) {
            if (!it.getUid().equals(curUser.getUid()) && !it.getUid().equals(tid)) {
                count++;
                ImageView imageView = new ImageView(this);
                wittingIconMap.put(it.getUid(), imageView);
                imageView.setLayoutParams(new RelativeLayout.LayoutParams(150, 150));
                ImageUtils.loadImage(imageView, it.getAvatar());
                wittingWraplayout.addView(imageView);
            }
            userMap.put(it.getUid(), it);
        }

        tvCallOther.setText("还有" + count + "人参与聊天");
    }

    private void createHelperAndJoin() {
        callOpera.answer(callId, channelId, true);
        videoRoomHelper = new YMVideoRoomHelper(
                this,
                curUser.getUid(),
                channel,
                new YMVideoRoomHelperLinstener() {
                    @Override
                    public void onLocalJoin(SurfaceView surfaceViewRenderer) {
                        onVideoMemberJoin(curUser.getUid(), surfaceViewRenderer);
                    }

                    @Override
                    public void onRemoteJoin(SurfaceView surfaceViewRenderer, String memberId) {
                        onVideoMemberJoin(memberId, surfaceViewRenderer);

                    }

                    @Override
                    public void onRemoteLeave(SurfaceView surfaceViewRenderer, String memberId) {
//                    binding.calling.wraplayout.removeView(surfaceViewRenderer)
                        onVideoMemberLeave(memberId);
                    }

                    public void didReciveOtherMessage(String msg, String meberId) {
                        if (msg.equals("closeCamera")) {
                            openCamera(meberId, false);
                        } else if (msg.equals("openCamera")) {
                            openCamera(meberId, true);
                        }
                    }

                });
        if (videoRoomHelper != null) {
            videoRoomHelper.join();
            videoRoomHelper.initLocal();
        }
        showJoin();
    }


    /**
     * 用户离开
     */
    private void onVideoMemberLeave(String memberId) {
        PersonalItemView view = personalMap.get(memberId);
        if (view != null) {
            callingWraplayout.removeView(view);
        }
    }

    /**
     * 用户进入
     */
    private void onVideoMemberJoin(String memberId, SurfaceView surfaceView) {
        surfaceView.setLayoutParams(new RelativeLayout.LayoutParams(-1, -1));
        if (personalMap.get(memberId) != null) {
            personalMap.get(memberId).showSurfaceView(surfaceView);
        }
    }

    /**
     * 用户关闭摄像头
     */
    private void openCamera(String memberId, Boolean open) {
        if (open) {
            if (personalMap.get(memberId) != null) {
                personalMap.get(memberId).hideIcon();
            }

        } else {
            if (personalMap.get(memberId) != null) {
                personalMap.get(memberId).showIcon();
            }
        }
    }

    /**
     * 开始播放音乐
     */
    private void startCallSound() {
//        val uri = Uri.parse(
//            "android.resource://" + App.INSTANCE.packageName
//                .toString() + "/" + R.raw.incoming_call_ring
//        )
//        ringPlayer.play(App.INSTANCE, uri, true, AudioManager.STREAM_RING)
    }

    /**
     * 停止播放音乐
     */
    private void stopCallSound() {
        ringPlayer.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopCallSound();
    }

    @Override
    public void onReceiveMessage(String peerId, String msg) {
        Log.e("zgj", "收到消息了${msg}" + msg);
    }

    @Override
    public void onMemberJoined(String peerId) {
        Log.e("zgj", "有人进来了${peerId}" + peerId);
    }

    @Override
    public void onMemberLeaved(String peerId) {
        Log.e("zgj", "有人走了${peerId}" + peerId);
        if (callId.equals(peerId)) {
            finish();
        }

        userMap.remove(peerId);
        ImageView view = wittingIconMap.get(peerId);
        if (view != null) {
            wittingWraplayout.removeView(view);
        }

        tvCallOther.setText("还有" + wittingIconMap.size() + "人参与聊天");
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}